//
//  RedBagService.swift
//  LeGou
//
//  Created by lxm on 2022/10/8.
//

import Foundation
class RedBagService {
    private init(){}
    static let shared = RedBagService()
    
    var diff = 0.0
    
    var getInfoDisposeBag = DisposeBag()
    
    var nowTimeinterval : Double {
        return Date().timeIntervalSince1970 + diff
    }
    
    var redBagData = ZMUtil.fastNilBehavior(type: RedBagModels.RedActivityData.self)
    
    func getDes() -> String {
        guard let redBagData = RedBagService.shared.redBagData.value else {return ""}
        if let now = redBagData.now, !checkOver(info: now) {
            return suiteDes(info: now)
        }
        if let wait = redBagData.wait, !checkOver(info: wait) {
            return suiteDes(info: wait)
        }
        return "已结束"
    }
    
    
    func suiteDes(info : RedBagModels.RedActivityInfo) -> String {
        guard let s = info.startTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"), let e = info.endTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"), let rs = info.realStartTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"), let re = info.realEndTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") else {
            return ""
        }
        if (s as NSDate).zm.isToday() {
            let diff = rs.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval
            if diff < 120, diff > 0 {
                let min = Int(diff) / 60
                let sec = Int(diff) % 60
                return "倒计时" + String(format: "%02d", min) + ":" + String(format: "%02d", sec) + "后开抢"
            } else if diff > 120 {
                return "\(s.zm.toString("HH:mm"))-\(e.zm.toString("HH:mm")) 随机出现"
            } else {
                let endDiff = re.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval
                if endDiff > 0 {
                    let min = Int(endDiff) / 60
                    let sec = Int(endDiff) % 60
                    return "距本轮红包结束仅剩" + String(format: "%02d", min) + ":" + String(format: "%02d", sec)
                } else {
                    return "已结束"
                }
            }
        } else if (s as NSDate).zm.isTomorrow() {
            return "明天 \(s.zm.toString("HH:mm"))-\(e.zm.toString("HH:mm")) 随机出现"
        } else {
            return "周\(s.zm.weekdayStr()) \(s.zm.toString("HH:mm"))-\(e.zm.toString("HH:mm")) 随机出现"
        }
    }
    
    // 获取红包信息
    func getRedBagInfo() {
        getInfoDisposeBag = DisposeBag()
        RedBagAPI.red_info.rxRequest(type: RedBagModels.RedActivityData.self).subscribe(onNext:{ [unowned self] resp in
            if let sys = resp.serverTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") {
                RedBagService.shared.diff = sys.timeIntervalSince1970 - Date().timeIntervalSince1970
            }
            self.redBagData.accept(resp)
        }).disposed(by: getInfoDisposeBag)
    }
    
    // 校验now场次是否已经过了
    func checkNowIsOver() -> Bool {
        // 如果是打开过了，那么就检查当前有没有结束有结束就重新加载
        guard let redBagData = redBagData.value, let now = redBagData.now else {return false}
        return checkOver(info: now)
    }
    
    // 检查某个活动是否结束
    func checkOver(info : RedBagModels.RedActivityInfo) -> Bool {
        guard let realEndTime = info.realEndTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") else {return false}
        return realEndTime.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval <= 0
    }
    
    func checkNowAndRefresh() {
        if checkNowIsOver() {
            if DebounceTool.shard.debounce("checkNowAndRefresh", 5) == false {return}
            getRedBagInfo()
        }
    }
    
    // 检查wati场次是不是成为now场次了，是的话就刷新
    func checkWaitIsBegin() {
        // wati的场次时间到了，那么需要刷新
        if checkWaitBegin() {
            if DebounceTool.shard.debounce("checkWaitIsBegin", 5) == false {return}
            getRedBagInfo()
        }
    }
    
    // 检查wati场次是不是成为now场次了
    func checkWaitBegin() -> Bool {
        guard let redBagData = redBagData.value, redBagData.now == nil, let wait = redBagData.wait, let startTime = wait.startTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") else {return false}
        return startTime.timeIntervalSince1970 - nowTimeinterval <= 0
    }
    
    // 检查是否需要自动更新
    func checkNeedAutoRefresh() {
        if checkNowIsOver() || checkWaitBegin() {
            if DebounceTool.shard.debounce("checkNeedAutoRefresh", 5) == false {return}
            getRedBagInfo()
        }
    }
    
    // 检查是否需要展示红包雨
    func checkNeedShowRedRain() {
        if !isInActivity() {return}
        guard let redBagData = redBagData.value,
              let now = redBagData.now else {return}
        let key = generateCacheKey(acId: now.id)
        // 有么有显示过这个key
        if let _ = UserDefaults.standard.object(forKey: key) as? String {
            return
        }
        // 当前是不是停留在首页
        if !(AppHelper.currentNav()?.children.last is HomeVC_V2) {
            return
        }
        UserDefaults.standard.setValue("1", forKey: key)
        showRedRain()
    }
    
    // 生成活动对应的缓存key
    func generateCacheKey(acId : Int) -> String {
        let date = nowTimeinterval.zm.toDate().zm.toString("YYYY-MM-dd")
        return "red-\(acId)-\(date)"
    }
    
    func markActivityRobed(acId : Int) {
        let key = generateCacheKey(acId: acId)
        UserDefaults.standard.setValue("1", forKey: key)
    }
    
    // 红包活动是否正在进行
    func isInActivity() -> Bool{
        guard let redBagData = redBagData.value,
              let now = redBagData.now,
              let realStartTime = now.realStartTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"),
              let endStartTime = now.realEndTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss")else {return false}
        return realStartTime.timeIntervalSince1970 < nowTimeinterval && endStartTime.timeIntervalSince1970 > nowTimeinterval
    }
    
    // 显示红包雨效果
    func showRedRain() {
        let v = ZMUtil.loadNibViewFullScreen(nibName: RedRainView.self)
        APPWindow?.addSubview(v)
    }
    
    // 前往红包VC
    func goRedBagVC() {
        if LoginService.shared.checkLogin() == false {return}
        let vc = RedBagVC()
        AppHelper.currentNav()?.pushViewController(vc, animated: true)
    }
    
    // 检查有没有资格抢红包
    func checkCanOpen(complete : @escaping ((_ ok : Bool)->())) {
        if DebounceTool.shard.debounce("onRedBag", 1) == false {return}
        
        complete(true)        
//        RedBagAPI.can_rob.rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
//            if JSON(resp)["hasPermit"].boolValue {
//                // 能抢红包
//                complete(true)
//            } else {
//                let v = ZMUtil.loadNibViewFullScreen(nibName: RedTaskView.self)
//                v.payCount = JSON(resp)["payCount"].intValue
//                v.invite = JSON(resp)["invite"].intValue
//                v.setUI()
//                APPWindow?.addSubview(v)
//            }
//        }).disposed(by: getInfoDisposeBag)
    }
    
    // 生成当前活动当前用户是否点击成功对应的缓存key
    func generateClicedCacheKey(acId : Int) -> String {
        let uid = ZMAppShareData.share.safeUserId
        let date = nowTimeinterval.zm.toDate().zm.toString("YYYY-MM-dd")
        return "red-\(acId)-\(date)-\(uid)"
    }
    
    // 标记该活动当前用户已经点击过了
    func markActivityClicked(acId : Int) {
        let key = generateClicedCacheKey(acId: acId)
        UserDefaults.standard.setValue("1", forKey: key)
    }
    
    // 是否点击过红包
    func isClicked(acId : Int) -> Bool {
        let key = generateClicedCacheKey(acId: acId)
        if let _ = UserDefaults.standard.object(forKey: key) as? String {
            return true
        } else {
            return false
        }
    }
}

